package com.bawei.detail.view

import android.graphics.Color
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.entity.MovieVideoEntity
import com.bawei.common.event.LiveDataBus
import com.bawei.common.event.LiveDataBusEvent
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.detail.R
import com.bawei.detail.adapter.DetailViewPagerAdapter
import com.bawei.detail.databinding.ActivityDetailBinding
import com.bawei.detail.entity.TabEntity
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser

@Route(path = RoutePath.PATH_DETAIL_PAGE)
@AndroidEntryPoint
class DetailActivity : BaseMviActivity<ActivityDetailBinding>() {

    @Autowired
    lateinit var movieEntity: MovieVideoEntity
    private var mMoviePlayer: StandardGSYVideoPlayer? = null
    private lateinit var mDanmuContext: DanmakuContext
    private var tabList = arrayListOf<CustomTabEntity>(TabEntity("简介", 0, 0))
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPagerAdapter: DetailViewPagerAdapter


    override fun getLayoutId(): Int = R.layout.activity_detail

    override fun initViews() {
        ARouter.getInstance().inject(this)
        //初始化GSYPlayer
        mMoviePlayer = mDataBinding.moviePlayer
        mMoviePlayer?.setUp(movieEntity.videopath, true, "")
        mMoviePlayer?.backButton?.visibility = View.GONE

        tabList.add(TabEntity("评论", 0,0))
        mDataBinding.tabLayout.setTabData(tabList)

        fragments.add(IntroduceFragment.newInstance(movieEntity.userid, movieEntity.videotypeid))
        fragments.add(CommendFragment.newInstance("7040684506063307271"))

        mPagerAdapter = DetailViewPagerAdapter(fragments, supportFragmentManager, lifecycle)
        mDataBinding.vp2.offscreenPageLimit = 1
        mDataBinding.vp2.adapter = mPagerAdapter

        //显示发送弹幕布局
        mDataBinding.tvDanmu.setOnClickListener {
            mDataBinding.llDanmuLayout.visibility = View.VISIBLE
        }

        //发送弹幕点击事件
        mDataBinding.ivDanmuSend.setOnClickListener {
            var msg = mDataBinding.etDanmuInput.editableText.toString().trim()
            if (msg.isNotEmpty()){
               sendDanmu(msg)
            }
        }

        //初始化弹幕
        initDanmu()

        //VP2和TabLayout联动
        mDataBinding.tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                mDataBinding.vp2.currentItem = position
            }
            override fun onTabReselect(position: Int) {

            }
        })

        mDataBinding.vp2.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                mDataBinding.tabLayout.currentTab = position
                if (position == 1){
                    (fragments[1] as CommendFragment).loadCommendData(movieEntity.userid)
                }
            }
        })

        //订阅列表相关操作
        LiveDataBus.with<LiveDataBusEvent>("movie_detail_options").observe(this@DetailActivity){
            handLiveDataEvent(it)
        }
    }


    private fun handLiveDataEvent(event: LiveDataBusEvent){
        movieEntity= event.data as MovieVideoEntity
        when(event.type){
            100 -> {
                mMoviePlayer?.setUp(movieEntity.videopath, true, "")
                mMoviePlayer?.startPlayLogic()
            }
        }
    }


    private fun initDanmu(){

        //创建弹幕的上下文对象
        mDanmuContext = DanmakuContext.create()
        //准备弹幕
        mDataBinding.danmuView.prepare(object : BaseDanmakuParser(){
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }, mDanmuContext)
        //设置弹幕回调事件
        mDataBinding.danmuView.setCallback(object : DrawHandler.Callback{
            override fun prepared() {

            }

            override fun updateTimer(timer: DanmakuTimer?) {

            }

            override fun danmakuShown(danmaku: BaseDanmaku?) {

            }

            override fun drawingFinished() {

            }
        })

    }



    private fun sendDanmu(msg: String){
        //清理历史弹幕
        mDataBinding.danmuView.clear()
        mDataBinding.danmuView.removeAllDanmakus(true)

        //创建弹幕实体对象
        var danmuEntity = mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
            text = msg
            textSize = 30f
            textColor = Color.RED
            padding = 10
            time = 1200
        }
        //添加到弹幕布局中
        mDataBinding.danmuView.addDanmaku(danmuEntity)

        //创建弹幕实体对象
        var danmuEntity1 = mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
            text = "第二条弹幕：${msg}"
            textSize = 30f
            textColor = Color.YELLOW
            padding = 10
            time = 800
        }
        mDataBinding.danmuView.addDanmaku(danmuEntity1)

        //启动弹幕
        mDataBinding.danmuView.start()

        //清理弹幕输入框
        mDataBinding.etDanmuInput.setText("")
        mDataBinding.llDanmuLayout.visibility = View.GONE
    }


    override fun onStart() {
        super.onStart()
        mMoviePlayer?.startPlayLogic()
    }

    override fun onResume() {
        super.onResume()
        mMoviePlayer?.onVideoResume()
    }

    override fun onPause() {
        super.onPause()
        mMoviePlayer?.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mMoviePlayer?.release()
        mMoviePlayer = null
    }

}